import { onMounted, ref } from "vue";
import request from "@/utils/request";
import { NotifyPlugin, } from 'tdesign-vue-next';

export function useTableData(queryUrl,delUrl,queryParams={}) {
    
    const data = ref([]);
    const loading = ref(false);
    const rows = ref(0);
    const params = ref(queryParams)
    const delParams = ref({id:0})

    const fetchData = () => {
        loading.value = true
    
        request.get(queryUrl,{
            ...params.value
        }).then(res=>{
            if(res.code===200){
               
                data.value = res.data
                rows.value = res.total
            }
        }).catch(error=>{
            console.log(error)
        }).finally(()=>{
            loading.value = false
        })
    }

    const deleteData = () =>{
       return new Promise((resolve,reject)=>{

            request.delete(delUrl,{
                ...delParams.value
            }).then(res=>{
                if(res.code===200){
                    NotifyPlugin.success({ title: '成功', content: '该数据已经删除', closeBtn:true })
                    resolve(true) 
                }
                
            }).catch(error=>{
                NotifyPlugin.warning({ title: '失败', content: '数据删除失败', closeBtn:true })
                reject(false)
            })

       })
        
    }

    onMounted(()=>{
        fetchData()
    })

    return {data,rows,params,delParams,loading,fetchData,deleteData}

}